# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：自定义异常
"""
# 错误处理（有错误）

from django.db import DatabaseError
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status


def my_exception_handler(exc, context):
    # 先调用 REST framework 默认的异常处理方法获得标准错误响应对象
    response = exception_handler(exc, context)
    if response is None:
        if isinstance(exc, DatabaseError):
            # 数据库异常
            response = Response({"code": 400, 'msg': f'数据库错误！错误原因：{exc}'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            response = Response({"code": 500, 'msg': f'服务器未知错误！错误原因:{exc}'},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return response

    msg = response.reason_phrase

    if isinstance(response.data, dict):
        if "detail" in response.data:
            msg = response.data["detail"]
        else:
            for k, v in response.data.items():
                if isinstance(v, list):
                    msg = v[0]
                else:
                    msg = v
    elif isinstance(response.data, list) and response.data:
        msg = response.data[0]
    else:
        msg = str(response.data)

    res = {}
    if isinstance(response.data, dict):
        res.update(response.data)
    res["msg"] = msg
    res["code"] = response.status_code

    if response.status_code == 204:
        res["msg"] = "删除成功！"
        return Response(res, status=status.HTTP_200_OK, exception=True)
    return Response(res, status=response.status_code, exception=True)
